this.addEventListener("message", function (e) {
  debugger;
  const data = e.data;
  const deviceName = data.deviceName;
  let imgSrc = data.src;
  imgSrc = this.dataURLtoBlob(imgSrc);

  var cvs = new OffscreenCanvas(100, 100);
  var ctx = cvs.getContext("2d");
  const compress = this.compressImage;
  let base64Url;
  this.createImageBitmap(imgSrc).then(function (ret) {
    // alert("加载完毕"); // 将图片画到canvas上面上去！
    cvs.width = ret.width;
    cvs.height = ret.height;
    ctx.drawImage(ret, 0, 0);

    const time = new Date().getTime();
    ctx.font = "40px 微软雅黑";
    ctx.fillStyle = "rgba(252,255,255,0.8)";
    ctx.fillText(`${time}`, 50, 50); //选择位置

    ctx.textAlign = "right";
    ctx.textBaseline = "bottom";
    ctx.fillText(`${deviceName}`, cvs.width, cvs.height);
    cvs.convertToBlob().then((ret) => {
      blobToDataURL(ret, (url) => {
        base64Url = url.replace("data:image/png;base64,", "");

        if (data.isDlydt) {
          postMessage(base64Url);
          this.close;
          return;
        }

        compress(
          (ret) => {
            postMessage(ret);
            this.close;
            // successBack && successBack(ret);
          },
          (ret) => {},
          base64Url,
          quality
        );
      });
    });
    // base64Url = cvs
    //   .toDataURL("image/base64")
    //   .replace("data:image/png;base64,", "");
    // document.body.removeChild(cvs);
  });
  //   img.onload = function () {

  //   };

  //   img.src = imgSrc;
});

function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function blobToDataURL(blob, callback) {
  var a = new FileReader();
  a.onload = function (e) {
    callback(e.target.result);
  };
  a.readAsDataURL(blob);
}

function compressImage(successBack, failBack, base64, quality) {
  navigator.mediaService.compressPicture(
    (ret) => {
      successBack && successBack(ret);
    },
    failBack,
    base64,
    quality ? quality : 30
  );
}
